<template>
  <div>
    <Modal
      class="market-dialog"
      :title="title"
      width="1024"
      footer-hide
      :value="value"
      :mask-closable="false"
      @on-cancel="handleCancel">
      <Form
        ref="form"
        :model="form"
        :rules="rules"
        :label-width="95"
        label-position="left">
        <FormItem :label="$t('m.chaLogo')" prop="logo">
<!--          //新增logo-->
          <Upload
            ref="upload"
            :show-upload-list="false"
            :format="['jpg','jpeg','png']"
            :before-upload="handleBeforeUpload"
            accept="image/jpeg,image/png"
            type="drag"
            action=""
            style="display: inline-block;width: 60px;vertical-align:middle;">
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <div class="upload-list" v-show="form.logo">
            <img :src="form.logo">
          </div>
        </FormItem>
        <Row>
          <Col span="11">
<!--            渠道名称-->
            <FormItem :label="$t('m.channelName')" prop="name">
<!--              输入渠道名称-->
              <Input type="text" :placeholder="this.$t('m.channelName')"  v-model="form.name" />
            </FormItem>
          </Col>
          <Col span="12" offset="1">
<!--            导流页面url-->
            <FormItem :label="$t('m.daoliuPage')" prop="link">
              <Input type="text" placeholder="Please enter Diversion page url" v-model="form.link" />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="11">
            <FormItem label="标题" prop="title">
              <Input type="text" placeholder="Please enter title" v-model="form.title" />
            </FormItem>
          </Col>
          <Col span="12" offset="1">
<!--            副标题-->
            <FormItem :label="$t('m.smti')" prop="subTitle">
              <Input type="text" :placeholder="this.$t('m.smti')" v-model="form.subTitle" />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="11">
<!--            最小借款额度,请输入最小借款额度-->
            <FormItem :label="$t('m.minLM')" prop="minLoanAmount">
              <Input type="text" :placeholder="this.$t('m.minLM')" v-model="form.minLoanAmount" number />
            </FormItem>
          </Col>
          <Col span="12" offset="1">
<!--            最大借款额度,请输入最大借款额度-->
            <FormItem :label="$t('m.maxLM')" prop="maxLoanAmount">
              <Input type="text" :placeholder="this.$t('m.maxLM')" v-model="form.maxLoanAmount" number />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="11">
<!--            借款期限  请输入借款期限（多个请用','分隔）-->
            <FormItem :label="$t('m.loanTimeLimit')" prop="loanPeriods">
              <Input type="text" :placeholder="this.$t('m.loanTimeLimit')" v-model="form.loanPeriods" />
            </FormItem>
          </Col>
          <Col span="12" offset="1">
<!--            日费率  请输入日费率（例如：0.0001）-->
            <FormItem :label="$t('m.dayRate')" prop="feeRateDaily">
              <Input type="text" :placeholder="this.$t('m.dayRate')" v-model="form.feeRateDaily" number />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <!-- <Col span="11">
            <FormItem label="热门标签" prop="sortNum">
              <Input type="text" placeholder="请输入数字（例如：1）" v-model="form.sortNum" number />
              <div class="form-item-info">
                <Icon type="ios-alert" size="14" color="#ff9900" class="icon-alert" />
                输入的数字越大，页面显示的位置越靠前
              </div>
            </FormItem>
          </Col> -->
          <Col span="11">
<!--            通过率  请输入通过率（例如：90%）-->
            <FormItem :label="$t('m.passRate')" prop="passRate">
              <Input type="text" :placeholder="this.$t('m.passRate')" v-model="form.passRate" />
            </FormItem>
          </Col>
          <Col span="12" offset="1">
<!--            申请人数  请输入申请人数-->
            <FormItem :label="$t('m.applyNum')" prop="applyNum">
              <Input type="text" :placeholder="this.$t('m.applyNum')" v-model="form.applyNum" number />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="11">
            <!-- <FormItem label="通过率" prop="passRate">
              <Input type="text" placeholder="请输入通过率（例如：90%）" v-model="form.passRate" />
            </FormItem> -->
<!--            <FormItem label="收费模式" prop="settleMode">-->
<!--              &lt;!&ndash; <Input type="text" placeholder="请输入收费模式（例如：CPA/15）" v-model="form.settleMode" /> &ndash;&gt;-->
<!--&lt;!&ndash;              <Select&ndash;&gt;-->
<!--&lt;!&ndash;                placeholder="请选择收费模式"&ndash;&gt;-->
<!--&lt;!&ndash;                v-model="form.settleMode">&ndash;&gt;-->
<!--&lt;!&ndash;                <Option&ndash;&gt;-->
<!--&lt;!&ndash;                  v-for="(item, index) in settleModeList"&ndash;&gt;-->
<!--&lt;!&ndash;                  :value="item"&ndash;&gt;-->
<!--&lt;!&ndash;                  :key="index">{{ item.settleMode}}</Option>&ndash;&gt;-->
<!--&lt;!&ndash;              </Select>&ndash;&gt;-->
<!--            </FormItem>-->
          </Col>
          <Col span="12" offset="1">
<!--            收费单价   请输入收费单价-->
            <FormItem :label="$t('m.chOC')" prop="settlePrice">
              <Input type="text" :placeholder="this.$t('m.chOC')" v-model="form.settlePrice" number />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="11">
<!--            标签  多个用';'隔开"-->
            <FormItem :label="$t('m.label')" prop="tags">
              <Input type="text" :placeholder="this.$t('m.label')" v-model="form.tags" />
            </FormItem>
          </Col>
          <Col span="12" offset="1">
            <FormItem :label="$t('m.ynShelf')" prop="status">
              <RadioGroup v-model="form.status">
                <Radio :label="1">{{this.$t('m.sjPay')}}</Radio>
                <Radio :label="0">{{this.$t('m.xjPay')}}</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
        </Row>

        <Row>
          <Col span="11">
            <FormItem :label="$t('m.homeJx')" prop="selected">
              <Input type="text" placeholder="请输入数字" v-model="form.selected" number />
              <div class="form-item-info">
                <Icon type="ios-alert" size="14" color="#ff9900" class="icon-alert" />
<!--                输入的数字大于0，表示精选，数字越大越靠前-->
                {{this.$t('m.sbs')}}
              </div>
            </FormItem>
          </Col>
          <Col span="12" offset="1">
            <FormItem :label="$t('m.tjLable')" prop="recommend">
              <Input type="text" placeholder="Please enter  number" v-model="form.recommend" number />
              <div class="form-item-info">
                <Icon type="ios-alert" size="14" color="#ff9900" class="icon-alert" />
<!--                输入的数字大于0，表示推荐，数字越大越靠前（推荐优先级高于热门）-->
                {{this.$t('m.sdk')}}
              </div>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="11">
<!--            热门标签   请输入数字（例如：1）-->
            <FormItem :label="$t('m.hotLabel')" prop="sortNum">
              <Input type="text" placeholder="Please enter number" v-model="form.sortNum" number />
              <div class="form-item-info">
                <Icon type="ios-alert" size="14" color="#ff9900" class="icon-alert" />
                输入的数字越大，页面显示的位置越靠前
              </div>
            </FormItem>
          </Col>
          <Col span="12" offset="1">
<!--            申请条件  请输入申请条件（用'<br>'表示换行） -->
            <FormItem :label="$t('m.qstj')" prop="applyCondition">
              <Input type="textarea" placeholder="Please enter  application conditions" :rows="6" v-model="form.applyCondition" />
            </FormItem>
          </Col>
        </Row>
        <Divider />
        <Row>
          <Col span="11">
<!--            后台地址  请输入管理后台地址-->
            <FormItem :label="$t('m.backUrl')" prop="backgroundUrl">
              <Input type="text" :placeholder="this.$t('m.qgt')" v-model="form.backgroundUrl" />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="11">
<!--            后台账号   请输入管理后台账号-->
            <FormItem :label="$t('m.baCC')" prop="backgroundUser">
              <Input type="text" :placeholder="this.$t('m.qscc')" v-model="form.backgroundUser" />
            </FormItem>
          </Col>
          <Col span="12" offset="1">
<!--            后台密码  请输入管理后台密码-->
            <FormItem :label="$t('m.backPassw')" prop="backgroundPwd">
              <Input type="text" :placeholder="this.$t('m.qsCP')" v-model="form.backgroundPwd" />
            </FormItem>
          </Col>
        </Row>
        <FormItem>
          <Button type="error"  @click="handleCancel" style="margin-right: 10px;">{{this.$t('m.cancel')}}</Button>
          <Button type="primary"  @click="handleSubmit" :loading="btnLoading">{{this.$t('m.tijiaoSub')}}</Button>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
  import qs from 'qs';
  import lrz from 'lrz';
  import { deepCopy } from '@/libs/util';

  export default {
    name: 'modalOperator',
    props: {
      title: String,
      type: String,
      value: {
        type: Boolean,
        default: false
      },
      formData: {
        type: Object,
        default: function() {
          return {
            name: '',
            logo: '',
            link: '',
            title: '',
            subTitle: '',
            minLoanAmount: '',
            maxLoanAmount: '',
            loanPeriods: '',
            feeRateDaily: '',
            applyNum: '',
            applyCondition: '',
            sortNum: '',
            tags: '',
            passRate: '',
            settleMode: '',
            settlePrice: '',
            selected: '',
            recommend: '',
            description: '',
            backgroundUrl: '',
            backgroundUser: '',
            backgroundPwd: ''
          }
        }
      }
    },
    data () {
      const validateNumber = (rule, value, callback) => {
        if (!Number.isInteger(value)) return callback(new Error('请输入数字'));
        return callback();
      }
      const validateDecimals = (rule, value, callback) => {
        let reg = /^\d+(\.\d{1,4})?$/;
        if (value <= 0 || value >= 1) {
          callback(new Error('请输入大于0且小于1的小数'));
        } else if (!reg.test(value)) {
          callback(new Error('小数位数最多保留四位'));
        } else {
          callback();
        }
      }
      return {
        btnLoading: false,
        form: {
          name: '',
          logo: '',
          link: '',
          title: '',
          subTitle: '',
          minLoanAmount: '',
          maxLoanAmount: '',
          loanPeriods: '',
          feeRateDaily: '',
          applyNum: '',
          applyCondition: '',
          sortNum: '',
          tags: '',
          passRate: '',
          settleMode: '',
          settlePrice: '',
          selected: '',
          recommend: '',
          description: '',
          backgroundUrl: '',
          backgroundUser: '',
          backgroundPwd: ''
        },
        rules: {
          logo: [
            { required: true, message: 'Select Image', trigger: 'change' }
          ],
          name: [
            { required: true, message: 'Please enter a channel name', trigger: 'blur' }
          ],
          link: [
            { required: true, message: 'Please enter  diversion page url', trigger: 'blur' }
          ],
          title: [
            { required: true, message: 'Please enter a title', trigger: 'blur' }
          ],
          subTitle: [
            { required: true, message: 'Please enter a subtitle', trigger: 'blur' }
          ],
          minLoanAmount: [
            { type: 'number', required: true, message: 'Please enter  number', trigger: 'blur' },
            { validator: validateNumber, trigger: 'blur' }
          ],
          maxLoanAmount: [
            { type: 'number', required: true, message: 'Please enter  number', trigger: 'blur' },
            { validator: validateNumber, trigger: 'blur' }
          ],
          loanPeriods: [
            { required: true, message: 'Please enter  loan term', trigger: 'blur' }
          ],
          feeRateDaily: [
            { type: 'number', required: true, message: 'Please enter a decimal and keep up to four decimal places', trigger: 'blur' },
            { validator: validateDecimals, trigger: 'blur' }
          ],
          applyCondition: [
            { required: true, message: 'Please enter  application conditions', trigger: 'blur' }
          ],
          applyNum: [
            { type: 'number', required: true, message: 'Please enter  number', trigger: 'blur' },
            { validator: validateNumber, trigger: 'blur' }
          ],
          passRate: [
            { required: true, message: 'Please enter  pass rate', trigger: 'blur' }
          ],
          settleMode: [
            { required: true, message: 'Please enter  charging mode', trigger: 'change' }
          ],
          settlePrice: [
            { type: 'number', required: true, message: 'Please enter  number', trigger: 'blur' },
            { validator: validateNumber, trigger: 'blur' }
          ],
          tags: [
            { required: true, message: 'Please enter a label', trigger: 'blur' }
          ],
          status: [
            { required: true, type: 'number', message: 'Please choose whether to put on shelves', trigger: 'change' }
          ],
          selected: [
            { type: 'number', required: true, message: 'Please enter  number', trigger: 'blur' },
            { validator: validateNumber, trigger: 'blur' }
          ],
          recommend: [
            { type: 'number', required: true, message: 'Please enter  number', trigger: 'blur' },
            { validator: validateNumber, trigger: 'blur' }
          ],
          sortNum: [
            { type: 'number', required: true, message: 'Please enter  number', trigger: 'blur' },
            { validator: validateNumber, trigger: 'blur' }
          ]
        },
        settleModeList: []
      }
    },
    watch: {
      value (newValue) {
        if (newValue) {
          this.getSettleMode();
          this.form = deepCopy(this.formData);
        }
      }
    },
    methods: {
      // 获取收费模式
      getSettleMode() {
        this.$http.get('/api/laocai/loan-market/list')
        .then((Response) => {

          this.settleModeList = Response.body.result.list
          // if (errcode == 0) {
          //   // this.settleModeList = Response.body.result.list;
          // }
        }, error => {});
      },
      // 表单提交
      handleSubmit () {
        const { form } = this.$refs;
        form.validate(valid => {
          if (valid) {
            let params = '';
            this.btnLoading = true;
            let url=`/api/laocai/loan-market/add`;
            if (this.type == 'edit') {
              params = `/${this.form.id}`;
              url= `/api/laocai/loan-market/update`;
            }
            this.$http.post(url, {
              ...this.form
            })
              .then((Response) => {
                if (Response.body.code == 0) {
                let msg = this.type === 'add' ? '新增渠道成功' : '编辑渠道成功';
                this.$Message.success(msg);
                this.$emit('ok');
              }
              this.btnLoading = false;
            }, error => {
              console.log(error.statusText);
            });
          }
        })
      },
      handleCancel () {
        this.$refs.form.resetFields();
        this.$emit('input', false);
      },
      handleBeforeUpload (file) {
				const reg = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
				const limit5 = file.size / 1024 / 1024 < 1;

				if (!reg.test(file.type)) {
					this.$Message.error('只能上传jpg, jpeg, png格式的图片');
					return false;
        }

				if (!limit5) {
					this.$Message.error('上传的图片不能超过1MB');
					return false;
        }

				// 压缩图片
				lrz(file)
				.then(res => {
					const { base64 } = res;
          this.form.logo = base64;
				})
				.catch(err => {
					this.$Message.error('压缩图片失败');
				})
				.always(res => {});

				return false;
			}
    }
  }
</script>

<style lang="scss">
  .market-dialog {
    .ivu-form .ivu-form-item-label {
      margin-bottom: 0;
    }

    .ivu-radio-wrapper {
      margin-bottom: 0;
    }

    .ivu-divider-horizontal {
      margin: 0 auto 24px;
    }

    textarea.ivu-input {
      font-size: 12px;
    }

    .form-item-info {
      font-size: 12px;
      color: #ff9900;
      .icon-alert {
        margin-top: -2px;
        margin-right: 2px;
      }
    }

    .form-justify {
      .ivu-form-item-content {
        display: flex;
        align-items: center;
        justify-content: space-around;
      }

      .form-justify-input {
        display: block;
        width: 45%;
      }
    }

    .upload-list {
      display: inline-block;
      margin-left: 4px;
      width: 60px;
      height: 60px;
      line-height: 60px;
      border-radius: 4px;
      overflow: hidden;
      background: #fff;
      position: relative;
      box-shadow: none;
      font-size: 0;
      text-align: center;
      vertical-align: middle;
      img	{
        width: 100%;
        height: 100%;
        border-radius: 4px;
      }
    }

    .upload-list-cover {
      display: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0,0,0,.6);
    }

    .upload-list:hover .upload-list-cover {
      display: block;
    }

    .upload-list-cover i {
      display: inline-block;
      color: #fff;
      font-size: 20px;
      cursor: pointer;
      margin: 0 4px;
      vertical-align: middle;
    }
  }
</style>
